package com.sin.j2me.framework;

import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.file.IllegalModeException;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;

import com.sin.j2me.common.ExceptionHandle;
import com.sin.j2me.util.Stack;

public class SinFramework {
	private static MIDlet miDlet = null;
	private static Display display = null;
	private static Stack stack = null;
	
	public static void initFramework(MIDlet miDlet) {
		SinFramework.miDlet = miDlet;
		SinFramework.display = Display.getDisplay(miDlet);
		SinFramework.stack = new Stack();
	}
	
	public static int startDisplay(Displayable dis) {
		if(miDlet == null){
			throw new IllegalModeException("Uninited framework");
		}
		if(stack.empty() || stack.top() != dis){
			stack.push(dis);
		}
		
		display.setCurrent(dis);
		return stack.size();
	}
	
	public static void setAlert(Alert alert){
		if(!stack.empty())
			display.setCurrent(alert, (Displayable)stack.top());
		else
			display.setCurrent(alert);
	}
	
	public static int finishDisplay(Displayable dis){
		if(!stack.empty() && stack.top() == dis){
			return finishDisplay();
		}
		return stack.size();
	}
	
	public static int finishDisplay(){
		stack.pop();
		if(stack.empty()){
			exit();
		}
		else{
			display.setCurrent((Displayable) stack.top());
		}
		return stack.size();
	}
	
	public static void exit(){
		miDlet.notifyDestroyed();
	}
	
	public static void openWeb(String url){
		try {
			miDlet.platformRequest(url);
		} catch (ConnectionNotFoundException e) {
			e.printStackTrace();
			ExceptionHandle.handle(e);
		}
	}
}
